<script setup lang="tsx">
import { reactive, ref } from 'vue';
import { NButton, NPopconfirm, NSpace, NTag } from 'naive-ui';
import { fetchReportList, deleteReport, publishReport, offlineReport } from '@/service/api';
import { useBoolean } from '@sa/hooks';
import ReportOperateDrawer from './modules/report-operate-drawer.vue';
import ReportPreviewModal from './modules/report-preview-modal.vue';

const { bool: loading, setTrue: startLoading, setFalse: endLoading } = useBoolean();
const { bool: operateDrawerVisible, setTrue: openOperateDrawer, setFalse: closeOperateDrawer } = useBoolean();
const { bool: previewModalVisible, setTrue: openPreviewModal, setFalse: closePreviewModal } = useBoolean();

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  name: '',
  reportType: '',
  status: null as number | null
});

// 表格数据
const tableData = ref<Api.DataPlatform.Report[]>([]);
const total = ref(0);

// 操作类型
const operateType = ref<'add' | 'edit'>('add');
const editingId = ref<number>();
const previewId = ref<number>();

// 报表类型选项
const reportTypeOptions = [
  { label: '报表', value: 'REPORT' },
  { label: '仪表盘', value: 'DASHBOARD' },
  { label: '大屏', value: 'SCREEN' }
];

// 状态选项
const statusOptions = [
  { label: '禁用', value: 0 },
  { label: '启用', value: 1 }
];

// 列配置
const columns = [
  { type: 'selection', width: 50 },
  { title: 'ID', key: 'id', width: 80 },
  { title: '报表名称', key: 'name', width: 200, ellipsis: { tooltip: true } },
  {
    title: '报表类型',
    key: 'reportType',
    width: 120,
    render: (row: Api.DataPlatform.Report) => {
      const typeMap: Record<string, { label: string; type: 'info' | 'success' | 'warning' }> = {
        REPORT: { label: '报表', type: 'info' },
        DASHBOARD: { label: '仪表盘', type: 'success' },
        SCREEN: { label: '大屏', type: 'warning' }
      };
      const config = typeMap[row.reportType] || { label: row.reportType, type: 'info' };
      return <NTag type={config.type}>{config.label}</NTag>;
    }
  },
  { title: '数据源', key: 'datasourceName', width: 150, ellipsis: { tooltip: true } },
  { title: '刷新间隔(秒)', key: 'refreshInterval', width: 120 },
  {
    title: '状态',
    key: 'status',
    width: 100,
    render: (row: Api.DataPlatform.Report) => {
      return <NTag type={row.status === 1 ? 'success' : 'error'}>{row.status === 1 ? '启用' : '禁用'}</NTag>;
    }
  },
  { title: '创建时间', key: 'createTime', width: 180 },
  {
    title: '操作',
    key: 'actions',
    width: 280,
    fixed: 'right' as const,
    render: (row: Api.DataPlatform.Report) => {
      return (
        <NSpace>
          <NButton size="small" onClick={() => handlePreview(row.id)}>
            预览
          </NButton>
          <NButton size="small" onClick={() => handleEdit(row.id)}>
            编辑
          </NButton>
          {row.status === 0 ? (
            <NButton size="small" type="success" onClick={() => handlePublish(row.id)}>
              发布
            </NButton>
          ) : (
            <NButton size="small" type="warning" onClick={() => handleOffline(row.id)}>
              下线
            </NButton>
          )}
          <NPopconfirm onPositiveClick={() => handleDelete([row.id])}>
            {{
              default: () => '确认删除该报表吗？',
              trigger: () => (
                <NButton size="small" type="error">
                  删除
                </NButton>
              )
            }}
          </NPopconfirm>
        </NSpace>
      );
    }
  }
];

// 查询列表
async function getList() {
  startLoading();
  try {
    const { data } = await fetchReportList(queryParams);
    if (data) {
      tableData.value = data.rows || [];
      total.value = data.total || 0;
    }
  } finally {
    endLoading();
  }
}

// 搜索
function handleSearch() {
  queryParams.pageNum = 1;
  getList();
}

// 重置
function handleReset() {
  Object.assign(queryParams, {
    pageNum: 1,
    pageSize: 10,
    name: '',
    reportType: '',
    status: null
  });
  getList();
}

// 新增
function handleAdd() {
  operateType.value = 'add';
  editingId.value = undefined;
  openOperateDrawer();
}

// 编辑
function handleEdit(id: number) {
  operateType.value = 'edit';
  editingId.value = id;
  openOperateDrawer();
}

// 预览
function handlePreview(id: number) {
  previewId.value = id;
  openPreviewModal();
}

// 删除
async function handleDelete(ids: number[]) {
  await deleteReport(ids);
  window.$message?.success('删除成功');
  getList();
}

// 发布
async function handlePublish(id: number) {
  await publishReport(id);
  window.$message?.success('发布成功');
  getList();
}

// 下线
async function handleOffline(id: number) {
  await offlineReport(id);
  window.$message?.success('下线成功');
  getList();
}

// 分页改变
function handlePageChange(page: number) {
  queryParams.pageNum = page;
  getList();
}

// 初始化
getList();
</script>

<template>
  <div class="h-full flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <NCard title="报表设计" :bordered="false" size="small" class="sm:flex-1-hidden card-wrapper">
      <template #header-extra>
        <NButton type="primary" size="small" @click="handleAdd">
          <icon-ic-round-plus class="mr-4px text-20px" />
          新增报表
        </NButton>
      </template>

      <!-- 搜索表单 -->
      <NSpace class="pb-12px" justify="space-between">
        <NSpace>
          <NInput v-model:value="queryParams.name" placeholder="报表名称" clearable style="width: 200px" />
          <NSelect
            v-model:value="queryParams.reportType"
            placeholder="报表类型"
            :options="reportTypeOptions"
            clearable
            style="width: 150px"
          />
          <NSelect
            v-model:value="queryParams.status"
            placeholder="状态"
            :options="statusOptions"
            clearable
            style="width: 120px"
          />
          <NButton type="primary" @click="handleSearch">
            <icon-ic-round-search class="mr-4px text-20px" />
            搜索
          </NButton>
          <NButton @click="handleReset">
            <icon-ic-round-refresh class="mr-4px text-20px" />
            重置
          </NButton>
        </NSpace>
      </NSpace>

      <!-- 表格 -->
      <NDataTable
        :columns="columns"
        :data="tableData"
        :loading="loading"
        :scroll-x="1400"
        :pagination="{
          page: queryParams.pageNum,
          pageSize: queryParams.pageSize,
          itemCount: total,
          showSizePicker: true,
          pageSizes: [10, 20, 50, 100],
          onUpdatePage: handlePageChange,
          onUpdatePageSize: (size: number) => {
            queryParams.pageSize = size;
            queryParams.pageNum = 1;
            getList();
          }
        }"
        class="sm:h-full"
      />
    </NCard>

    <!-- 操作抽屉 -->
    <ReportOperateDrawer
      v-model:visible="operateDrawerVisible"
      :operate-type="operateType"
      :row-id="editingId"
      @success="getList"
    />

    <!-- 预览模态框 -->
    <ReportPreviewModal v-model:visible="previewModalVisible" :report-id="previewId" />
  </div>
</template>
